using UnityEngine;
using System.Collections.Generic;
using System;
using System.Reflection;
using Skills;
using Entities;

public class PlayerAttack : MonoBehaviour {
	
	public Color playerColor;
	public Material mat;
	private float skillTimer = 0;
	private Skill currentSkill = null;
	private Player player;
	private int comboCount;
	private Dictionary<KeyCode, Type> skillKeyMap;
	
		
	// Use this for initialization
	void Start () {
		mat = renderer.material;
		playerColor = mat.color;
		player = new Player();
		comboCount = 0;
		skillKeyMap = new Dictionary<KeyCode, Type>();
		skillKeyMap[KeyCode.A] = typeof(MeleeAttack);
	}
	
	// Update is called once per frame
	void Update () {
		if (skillTimer > 0) {
			skillTimer -= Time.deltaTime;
			if (skillTimer < currentSkill.getTotalDuration() - currentSkill.getDuration() - currentSkill.getStartUpDuration() ||
				skillTimer > currentSkill.getTotalDuration() - currentSkill.getStartUpDuration()) 
					mat.color = Color.yellow;
			else mat.color = Color.red;
		}
		else {
			skillTimer = 0;
			mat.color = playerColor;
			currentSkill = null;
			comboCount = 0;
		}
		
		foreach(KeyCode code in skillKeyMap.Keys){
			Type skill = skillKeyMap[code];
			CancelMode defaultMode = (CancelMode) skill.GetField("defaultMode", BindingFlags.Public | BindingFlags.Static).GetValue(null);
			if(Input.GetKeyDown(code)){
				if (skillTimer == 0){
					currentSkill = (Skill)Activator.CreateInstance(skill);
					skillTimer = currentSkill.getTotalDuration();
					comboCount = 1;
				} else if (currentSkill != null  
							&& skillTimer < currentSkill.getCancelTime() 
							&& currentSkill.getCancelMode() != CancelMode.finisher  
							&& defaultMode != CancelMode.starter
						)
					{
					
					currentSkill = (Skill)Activator.CreateInstance(skill);
					skillTimer = currentSkill.getTotalDuration();
					comboCount++;
					if (comboCount == player.getComboLimit()){
						currentSkill.setCancelMode(CancelMode.finisher);
					}
				}
			}
		}
	}
}
